import React, { useState, useRef } from 'react';
import { Stage, Layer, Rect, Circle, Text } from 'react-konva';

const CanvasArea = () => {
  const stageRef = useRef(null);
  const [scale, setScale] = useState(1);
  const [position, setPosition] = useState({ x: 0, y: 0 });
  const [isDragging, setIsDragging] = useState(false);
  const [lastPointerPosition, setLastPointerPosition] = useState({ x: 0, y: 0 });

  // 处理滚轮缩放
  const handleWheel = (e) => {
    e.evt.preventDefault();
    
    const scaleBy = 1.1;
    const stage = stageRef.current;
    const oldScale = scale;
    const pointer = stage.getPointerPosition();
    
    const mousePointTo = {
      x: (pointer.x - position.x) / oldScale,
      y: (pointer.y - position.y) / oldScale,
    };

    const newScale = e.evt.deltaY > 0 ? oldScale / scaleBy : oldScale * scaleBy;
    
    setScale(newScale);
    setPosition({
      x: pointer.x - mousePointTo.x * newScale,
      y: pointer.y - mousePointTo.y * newScale,
    });
  };

  // 处理拖拽开始
  const handleDragStart = (e) => {
    setIsDragging(true);
    setLastPointerPosition({
      x: e.evt.clientX,
      y: e.evt.clientY
    });
  };

  // 处理拖拽移动
  const handleDragMove = (e) => {
    if (!isDragging) return;
    
    const dx = e.evt.clientX - lastPointerPosition.x;
    const dy = e.evt.clientY - lastPointerPosition.y;
    
    setPosition({
      x: position.x + dx,
      y: position.y + dy
    });
    
    setLastPointerPosition({
      x: e.evt.clientX,
      y: e.evt.clientY
    });
  };

  // 处理拖拽结束
  const handleDragEnd = () => {
    setIsDragging(false);
  };

  return (
    <div 
      style={{
        width: '100%',
        height: '100%',
        background: '#f5f5f5',
        overflow: 'hidden',
        cursor: isDragging ? 'grabbing' : 'grab'
      }}
    >
      <Stage
        width={window.innerWidth - 80} // 减去侧边栏宽度
        height={window.innerHeight - 50} // 减去顶部栏高度
        ref={stageRef}
        scaleX={scale}
        scaleY={scale}
        x={position.x}
        y={position.y}
        onWheel={handleWheel}
        onMouseDown={handleDragStart}
        onMouseMove={handleDragMove}
        onMouseUp={handleDragEnd}
        onMouseLeave={handleDragEnd}
      >
        <Layer>
          {/* 示例图形 - 矩形 */}
          <Rect
            x={100}
            y={100}
            width={200}
            height={150}
            fill="#4CAF50"
            stroke="#2E7D32"
            strokeWidth={2}
          />
          
          {/* 示例图形 - 圆形 */}
          <Circle
            x={300}
            y={200}
            radius={50}
            fill="#2196F3"
            stroke="#0D47A1"
            strokeWidth={2}
          />
          
          {/* 示例文本 */}
          <Text
            x={150}
            y={300}
            text="可拖拽和缩放画布"
            fontSize={24}
            fill="#333"
          />
        </Layer>
      </Stage>
    </div>
  );
};

export default CanvasArea;